<?php


namespace common\service;


use Exception;
use common\model\UserModel;
use support\SingletonTrait;
use common\model\ProjectMemberModel;

class ProjectMemberService
{
    use SingletonTrait;

    /**
     * 查询用户项目成员角色
     * @param $userId
     * @param $filter
     * @return array|false|mixed|string
     */
    public function getUserProjectMemberRole($userId, $filter = [])
    {
        $filter['user_id'] = $userId;
        return model(ProjectMemberModel::class)
            ->where($filter)
            ->field('project_id,role_code')
            ->group('project_id,role_code')
            ->select();
    }

    /**
     * 多项目角色用户列表
     * @param $param
     * @param $filter
     * @param $page
     * @return array|false|mixed|string
     */
    public function roleUserList($param, $filter, $page)
    {
        $userIdList = model(ProjectMemberModel::class)
            ->join("user on user.id = project_member.user_id")
            ->where($filter)
            ->field('user.id')
            ->group('user.id')
            ->page($page[0], $page[1])
            ->order('user.created')
            ->column('id');
        if (empty($userIdList)) {
            return [];
        }

        return model(UserModel::class)
            ->where(['id' => ['IN', $userIdList]])
            ->field('id,name,avatar,uuid')
            ->select();
    }

    /**
     * 添加项目成员
     * @param int $userId 用户id
     * @param int $projectId 项目id
     * @param string $roleCode 角色code
     * @param int $roleId 角色id
     * @param string $type 类型:管理组、生产组
     * @param string $stepCategoryIds 环节id
     * @param int $teamId 团队id
     * @return array|bool
     * @throws Exception
     */
    public function add(int $userId, int $projectId, string $roleCode, int $roleId, string $type, string $stepCategoryIds = '', int $teamId = 0)
    {
        $data['project_id'] = $projectId;
        $data['user_id'] = $userId;
        $data['role_code'] = $roleCode;
        $data['role_id'] = $roleId;
        $data['type'] = $type;
        $data['step_category_ids'] = $stepCategoryIds;
        $data['team_id'] = $teamId;
        return model(ProjectMemberModel::class)->addItem($data);
    }

    /**
     * 批量添加项目成员
     * @param array $dataList
     * @param string $type
     * @param int $projectId
     * @return array
     * @throws Exception
     */
    public function addAll(array $dataList, string $type, int $projectId)
    {
        $res = [];
        $projectMemberList = model(ProjectMemberModel::class)->where(['project_id' => $projectId, 'type' => $type])->select();
        foreach ($projectMemberList as &$projectMember) {
            $projectMember['unique_key'] = "user_id:{$projectMember['user_id']};role_code:{$projectMember['role_code']};role_id:{$projectMember['role_id']};step_category_ids:{$projectMember['step_category_ids']};team_id:{$projectMember['team_id']}";
        }
        $projectMemberList = array_column($projectMemberList, null, 'unique_key');

        foreach ($dataList as $data) {
            $uniqueKey = "user_id:{$data['user_id']};role_code:{$data['role_code']};role_id:{$data['role_id']};step_category_ids:{$data['step_category_ids']};team_id:{$data['team_id']}";
            if (isset($projectMemberList[$uniqueKey])) {
                continue;
            }
            $res[] = $this->add($data['user_id'], $projectId, $data['role_code'], $data['role_id'], $type, $data['step_category_ids'], $data['team_id']);
        }
        return $res;
    }

    /**
     * 查询用户列表
     * @param $filter
     * @return array|mixed
     */
    public function getUserIdList($filter)
    {
        return model(ProjectMemberModel::class)->where($filter)->field('user_id')->group('user_id')->column('user_id');
    }

    /**
     * 查询用户列表
     * @param $filter
     * @return array|mixed
     */
    public function getUserList($filter)
    {
        $userIdList = model(ProjectMemberModel::class)->where($filter)->field('user_id')->group('user_id')->column('user_id');
        if (empty($userIdList)) {
            return [];
        }
        return UserService::getInstance()->selectLocalUserList(['id' => ['IN', implode(',', $userIdList)]]);
    }

    public function removeProjectMember($pmIdList)
    {
        if (!is_array($pmIdList)) {
            $pmIdList = explode(',', $pmIdList);
        }
        $updateData = [];
        foreach ($pmIdList as $projectMemberId) {
            $updateData[] = [
                'id' => $projectMemberId,
                'is_delete' => 1
            ];
        }
        model(ProjectMemberModel::class)->saveAll($updateData);
        return 0;
    }
}
